# c1
import numpy as np
from collections import defaultdict
from operator import itemgetter

valid_rules = defaultdict(int)
invalid_rules = defaultdict(int)
num_occurances = defaultdict(int)

dataset_filename = r"D:\jb51.net\Code_REWRITE\Chapter 1\affinity_dataset.txt"
X = np.loadtxt(dataset_filename)

buy_apple_person = 0
buy_banana_person = 0

for i in X:
    if i[3] == 1:
        buy_apple_person += 1
    if i[4] == 1:
        buy_banana_person += 1
# 进入循环
for sample in X:
    for premise in range(5):
        # 如果没有买，就跳出循环
        if sample[premise] == 0:
            continue
        # 如果买了，就计数+1，统计结果是各类物品买了数量
        num_occurances[premise] += 1
        # 统计相关性，买了改水果，买了另一个水果的数量
        for conclusion in range(5):
         if premise == conclusion:
             continue
         if sample[conclusion] == 1:
            valid_rules[(premise, conclusion)] += 1
         else:
            invalid_rules[(premise, conclusion)] += 1
# 支持度，统计的是合法数据
support = valid_rules
# 置信度，统计的是支持度除以统计总数
confidence = defaultdict(float)
for premise, conclusion in valid_rules.keys():
     rule = (premise, conclusion)
     confidence[rule] = valid_rules[rule] / num_occurances[premise]

sorted_support = sorted(support.items(), key=itemgetter(1), reverse=True)
sorted_confidence = sorted(confidence.items(), key=itemgetter(1), reverse=True)
print(sorted_support,sorted_confidence)